package com.xhsj.user.sms.transfer.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhsj.user.generalprocess.entity.TbPamGeneralProcessTask;
import com.xhsj.user.generalprocess.mapper.TbPamGeneralProcessHiTaskMapper;
import com.xhsj.user.generalprocess.mapper.TbPamGeneralProcessTaskMapper;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.pms.patent.domain.TbPamOverseasApply;
import com.xhsj.user.pms.patent.mapper.TbPamOverseasApplyMapper;
import com.xhsj.user.pms.patent.service.impl.TbPamInventorProposalIprServiceImpl;
import com.xhsj.user.sms.base.BaseService;
import com.xhsj.user.sms.process.entity.TbPurchaseProcessTask;
import com.xhsj.user.sms.process.mapper.TbPurchaseProcessTaskMapper;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseOrderMapper;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseOrderSubtaskMapper;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseTaskMapper;
import com.xhsj.user.sms.purchase.query.PatentInfoQuery;
import com.xhsj.user.sms.purchase.service.TbPurchaseOrderService;
import com.xhsj.user.sms.transfer.entity.TbTaskTransfer;
import com.xhsj.user.sms.transfer.mapper.TbTaskTransferMapper;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

/**
 * <p>
 * 任务转让 服务实现类
 * </p>
 *
 * @author suxiaolin
 * @since 2020-07-01
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbTaskTransfer")
public class TbTaskTransferService extends BaseService<TbTaskTransferMapper, TbTaskTransfer>{
    @Autowired
    private TbTaskTransferMapper dao;

    @Autowired
    private TbPurchaseTaskMapper tbPurchaseTaskMapper;
    @Autowired
    private TbPurchaseProcessTaskMapper tbPurchaseProcessTaskMapper;
    @Autowired
    private TbPurchaseOrderMapper tbPurchaseOrderMapper;

    @Autowired
    private TbPurchaseOrderSubtaskMapper tbPurchaseOrderSubtaskMapper;

    @Autowired
    private TbPamInventorProposalIprServiceImpl tbPamInventorProposalIprServiceImpl;

    @Autowired
    private TbGlobalUserMapper userMapper;

    @Autowired
    private TbPamGeneralProcessTaskMapper tbPamGeneralProcessTaskMapper;

    @Autowired
    private TbPamGeneralProcessHiTaskMapper tbPamGeneralProcessHiTaskMapper;

    @Autowired
    private TbPamOverseasApplyMapper tbPamOverseasApplyMapper;

    @Value("${ipr.iprName}")
    private String iprName;

    @Override
    //@CacheEvict(cacheNames="TbTaskTransfer", allEntries=true)
    public boolean save(TbTaskTransfer entity) {

        List<Integer> userList = entity.getUserList();
        entity.setDeptId(userList.get(0));
        entity.setUserId(userList.get(1));
        entity.setUpdateBy(entity.getCreateBy());
        return super.save(entity);
    }

    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbTaskTransfer getById(Serializable id) {
        return super.getById(id);
    }

    @Override
    //@CacheEvict(cacheNames="TbTaskTransfer", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

    //@Cacheable(key = "#data",sync = true)
    public IPage<TbTaskTransfer> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        TbTaskTransfer entity = JSON.parseObject(JSON.toJSONString(data), TbTaskTransfer.class);
        Page<TbTaskTransfer> page = new Page(currentPage,pageSize);
        QueryWrapper<TbTaskTransfer> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

    @Override
    //@Cacheable(value = "TbTaskTransfer",sync = true)
    public List<TbTaskTransfer> selectAll() {
        return super.selectAll();
    }


    //接收
    public boolean receiveTask(List<TbTaskTransfer> data) throws Exception {
        for (TbTaskTransfer tbTaskTransfer:data) {
            Integer modelType = tbTaskTransfer.getModelType();
            Integer taskType = tbTaskTransfer.getTaskType();
            String applyType = tbTaskTransfer.getApplyType();
            //专利个人任务接收
            int result=0;
            if(modelType==0 && taskType==0) {
                result=dao.receiveMyTaskByPatent(tbTaskTransfer.getDataId(),tbTaskTransfer.getUserId());
            }else if(modelType==0 && taskType==1){
                // 专利审批任务接收正在执行的表
                result=dao.receiveAduitTaskByPatent(tbTaskTransfer.getDataId(),tbTaskTransfer.getUserId());
                // 修改专利审批任务接收历史表
                int resultHi=dao.receiveAduitHiTaskByPatent(tbTaskTransfer.getDataId(),tbTaskTransfer.getUserId());
                if(resultHi==0){
                    throw new Exception("修改专利审批任务接收历史表失败");
                }
                // 获取交底书所在的节点
                PatentInfoQuery patentNodeId = dao.getPatentNodeId(tbTaskTransfer.getDataId());
                // 获取ipr列表
                List<Long> maps = userMapper.getPatentDepartUserList(iprName);
                // 判断转出者是否是技术负责人选定的ipr
                Long checkIpr = dao.getCheckIpr(patentNodeId.getIdentitylinkForDisclosure());
                // 判断接收者是否是ipr与转出者是否是ipr
                if (String.valueOf(checkIpr).equals(tbTaskTransfer.getCreateBy()) && maps.contains(Long.valueOf(tbTaskTransfer.getUserId()))) {
                    // 修改技术负责人选定的IPr
                    dao.updateCheckIpr(patentNodeId.getIdentitylinkForDisclosure(),tbTaskTransfer.getUserId(),tbTaskTransfer.getCreateBy());
                if (patentNodeId.getIdentitylinkForNode().equals("3AE5CBF5E43E444D8256929EC6BFF2C8")||
                    patentNodeId.getIdentitylinkForNode().equals("67409ADFDC384E46AA3F6B410113E495")||
                    patentNodeId.getIdentitylinkForNode().equals("39DB703EDD0A4A20AF858FBBED6BF6ED") ||
                    patentNodeId.getIdentitylinkForNode().equals("7524DFC3666B40C5A6E6EEFD063F06EA") ||
                    patentNodeId.getIdentitylinkForNode().equals("97BF5B1F73414EA9BBDB55C62D46B981")) {
                    // 修改创建者建议的ipr
                    tbPamInventorProposalIprServiceImpl.updateByDisclosureId(patentNodeId.getIdentitylinkForDisclosure(),tbTaskTransfer.getUserId(),tbTaskTransfer.getCreateBy());
                }
                }
            }
            //证章模块
            Map<String,Object> map=new HashMap();
            map.put("dataId",tbTaskTransfer.getDataId());
            if(modelType==1 && taskType==0 && "use_apply".equals(applyType)){  //模块证章个人任务
                result=dao.receiveMyTaskByBadges(tbTaskTransfer.getDataId(),tbTaskTransfer.getUserId());
                if(result==0){
                    throw new Exception("模块证章个人任务错误");
                }
                //合同证章正在执行表的申请人
                map.put("proposerId",tbTaskTransfer.getUserId());
                result=dao.receiveMyTaskByBadgesExce(map);
            }else if(modelType==1 && taskType==1 && ("use_audit".equals(applyType) ||  "contract_audit".equals(applyType) )){ //模块证章审批任务
                //合同证章正在执行表的指派人
                map.put("createBy",tbTaskTransfer.getUserId());
                result=dao.receiveAduitTaskByBadgesExce(map);
            }

            //合同模块
            if(modelType==1 && taskType==0 && "contract_apply".equals(applyType)){  //模块合同个人任务
                result=dao.receiveMyTaskByContract(tbTaskTransfer.getDataId(),tbTaskTransfer.getUserId());
                if(result==0){
                    throw new Exception("模块证章个人任务错误");
                }
                map.put("proposerId",tbTaskTransfer.getUserId());
                result=dao.receiveMyTaskByBadgesExce(map);
            }

            // 供应链模块
            if (modelType == 2) {
                result= receivePurchaseTask(tbTaskTransfer);
            }

            if(result==0){
                throw new Exception("任务接收失败");
            }
            tbTaskTransfer.setReceivingStatus(1);  //接收状态
            //修改转入任务表中的状态
            int i = dao.updateById(tbTaskTransfer);
            if(i==0){
                throw new Exception("任务接收失败");
            }
        }

//       if(!super.updateBatchById(data)){
//           throw new Exception("任务接收失败");
//       }
         return true;
    }

    /**
     * 接收供应链任务
     * @author 苏小林
     * @date 2020/7/2 17:49
     * @param: tbTaskTransfer
     * @return: int
     */
    private int receivePurchaseTask(TbTaskTransfer tbTaskTransfer) {
        Integer taskType = tbTaskTransfer.getTaskType();
        int result = 1;
        switch (taskType) {
            case 0 : //个人任务
                String applyType = tbTaskTransfer.getApplyType();
                if ("purchase_apply".equals(applyType)) { // 采购申请
                    int u = tbPurchaseTaskMapper.updateCreateBy(tbTaskTransfer.getUserId(),tbTaskTransfer.getDataId());
                    if (u == 0) {
                        result = 0;
                    }
                    TbPurchaseProcessTask tbPurchaseProcessTask = tbPurchaseProcessTaskMapper.getByDataId(tbTaskTransfer.getDataId());
                    if (tbPurchaseProcessTask !=null) {
                        int u1 = tbPurchaseTaskMapper.updateProposerIdByDataId(tbTaskTransfer.getUserId(),tbTaskTransfer.getDataId());
                        if (u1 == 0) {
                            result = 0;
                        }
                    }
                }

                if ("order_apply".equals(applyType)) { // 采购订单
                    // 修改采购订单
                    int i = tbPurchaseOrderMapper.updateCreateBy(tbTaskTransfer.getUserId(),tbTaskTransfer.getDataId());
                    if (i == 0) {
                        result = 0;
                    }
                    // 查询订单下游数据
                    Map<String,Object> map = tbPurchaseOrderMapper.getDownstreamData(tbTaskTransfer.getDataId());
                    // 子订单id
                    String subTaskId = StringUtils.getStringValue(map, "subTaskId");
                    // 订单在流程中的dataId
                    String orderProcessDataId = StringUtils.getStringValue(map, "orderProcessDataId");
                    // 子订单在流程中的dataId
                    String subTaskProcessDataId = StringUtils.getStringValue(map, "subTaskProcessDataId");

                    if (StringUtils.isNotBlank(subTaskId)) {
                        // 修改采购子任务
                        int i1 = tbPurchaseOrderSubtaskMapper.updateByOrderId(tbTaskTransfer.getUserId(), tbTaskTransfer.getDataId());
                        if (i1 == 0) {
                            result = 0;
                        }
                    }

                    if (StringUtils.isNotBlank(orderProcessDataId)) {
                        int i2 = tbPurchaseTaskMapper.updateProposerIdByDataId(tbTaskTransfer.getUserId(),orderProcessDataId);
                        if (i2 == 0) {
                            result = 0;
                        }
                    }

                    if (StringUtils.isNotBlank(subTaskProcessDataId)) {
                        int i3 = tbPurchaseTaskMapper.updateProposerIdByDataId(tbTaskTransfer.getUserId(),subTaskProcessDataId);
                        if (i3 == 0) {
                            result = 0;
                        }
                    }
                }
                break;
            case 1: // 审核任务
                int i3 = tbPurchaseTaskMapper.updateUserIdById(tbTaskTransfer.getUserId(),tbTaskTransfer.getDataId());
                if (i3 == 0) {
                    result = 0;
                }
                break;
        }
        return result;
    }

    //任务转让
    public boolean saveTbTaskTransfer(List<TbTaskTransfer> data) {
        for (TbTaskTransfer entity:data) {
            List<Integer> userList = entity.getUserList();
            if(StringUtils.isBlank(entity.getId())){
                entity.setId(IdGen.uuid());
                entity.setCreateDate(new Date());
            }
            entity.setDeptId(userList.get(0));
            entity.setUserId(userList.get(1));
            entity.setUpdateBy(entity.getCreateBy());
        }
        return super.saveOrUpdateBatch(data);
    }

    //拒绝
    public boolean refuseTask(List<String> data) throws Exception {
//        List<TbTaskTransfer> list=new ArrayList<>();
//        for (String id: data) {
//            TbTaskTransfer tbTaskTransfer=new TbTaskTransfer();
//            tbTaskTransfer.setId(id);
//            tbTaskTransfer.setReceivingStatus(2);
//            list.add(tbTaskTransfer);
//        }
        if(dao.revokeTask(data)!=data.size()){
            throw new Exception("拒绝失败");
        }
        return true;
//        return  super.updateBatchById(list);
    }

    //撤销
    public boolean revokeTask(List<String> data) throws Exception {
        if(dao.revokeTask(data)!=data.size()){
            throw new Exception("撤销失败");
        }
        return true;
    }

    /**
     * 接收海外申请专利
     * @author 苏小林
     * @date 2021/6/24 13:14
     * @param: data
     */
    public void receiveOverseasApply(List<Map<String, String>> data) throws Exception {
        for (Map<String, String> datum : data) {
            String processTaskId = datum.get("processTaskId");
            String transferId = datum.get("transferId");
            String taskType = datum.get("taskType");
            if (StringUtils.isBlank(processTaskId) || StringUtils.isBlank(transferId) || StringUtils.isBlank(taskType)) {
                throw new Exception("参数不全");
            }

            // 1、删除转让转让表
            dao.revokeTask(Arrays.asList(transferId));
            int i = Integer.parseInt(taskType);
            if (i == 0) { // 个人任务
                TbPamOverseasApply tbPamOverseasApply = new TbPamOverseasApply();
                tbPamOverseasApply.setId(Long.parseLong(processTaskId));
                tbPamOverseasApply.setCreateBy(UserUtils.getLoginAppUser().getUserId());
                tbPamOverseasApplyMapper.updateById(tbPamOverseasApply);

            } else {

                // 2、修改正在执行中任务接收人
                tbPamGeneralProcessTaskMapper.updateUserIdAndRoleId(Long.parseLong(processTaskId),UserUtils.getLoginAppUser().getUserId(),null);

                TbPamGeneralProcessTask processTask = tbPamGeneralProcessTaskMapper.selectById(Long.parseLong(processTaskId));
                if (processTask != null) {
                    // 3、修改历史任务
                    tbPamGeneralProcessHiTaskMapper.updateUserIdAndRoleId(processTask.getDataId(),processTask.getNodeId(),processTask.getProcessType(),UserUtils.getLoginAppUser().getUserId(),null);
                }
            }
        }

    }
}
